﻿using System;
using System.Data;
using System.Collections.Generic;
using System.Linq;
using System.Text;
using Jumpton.Data;
using Jumpton.Persistent;
using Jumpton.SFA.Server.Entity;

namespace Jumpton.SFA.Server.BusinessRule.System
{
    public class UserRoleManager:BusinessLogic
    {

        /// <summary>
        /// 获取用户所具有的角色
        /// </summary>
        /// <param name="UserID">用户编号</param>
        /// <param name="Include">包含不存在的组</param>
        /// <returns></returns>
        public DataTable GetRoleWithUser(decimal UserID,decimal DomainID, bool Include)
        {
            string Sqlstr;
            //decimal sysGroupID;
            if (Include)
            {
                Sqlstr = @"select * from user_groups u inner join sys_user_roles r on u.id=r.ROLE_NO where r.ACTIVE=1 and u.Active=1
                            and u.DOMAIN_ID='" + DomainID + "' and r.user_id='" + UserID + "'";

                //sysGroupID=int.Parse(new GroupManager().Load("系统").Rows[0]["id"].ToString());
                //if (Load(UserID, sysGroupID)==null)
                //    Sqlstr += " and id <>'" + sysGroupID + "'";
            }
            else
            {
                Sqlstr = @"with ColumnCTE ( id,parentdomainid,code,sysname,sys_id_no,level)
                as
                (
                select id, parentdomainid,code,sys_name as 'sysname',sys_id_no,0 as level from domains where id = " + DomainID.ToString() + @"
                union all select tt.id,tt.parentdomainid,tt.code,tt.sys_name as 'sysname',tt.sys_id_no,level+1 from domains tt join ColumnCTE cte on tt.id = cte.parentdomainid
                 and tt.active=1
                ) select u1.id,u1.code,u2.sequence_no,u2.active from user_groups u1   left join sys_user_roles u2 on u1.id=u2.role_no left join ColumnCTE u3 on u3.id=u1.domain_id where u3.id=u1.domain_id and  u1.active=1 and u2.active=1 and u2.user_id=" + UserID.ToString();
            }
            
           
            return Jumpton.Data.SqlData.OpenSql(Sqlstr).Tables[0];
        }


        public UserRole Load(decimal ID)
        {
            return (UserRole)Jumpton.Persistent.ObjectRow.Load(typeof(UserRole), "Sequence_no=" + ID);
        }


        public UserRole Load(decimal UserID, decimal RoleID)
        {
            return (UserRole)Jumpton.Persistent.ObjectRow.Load(typeof(UserRole), string.Format("role_no={0} and user_id={1}" ,RoleID,UserID));
        }

        public void Delete(decimal userID)
        {
            SqlData.ExecuteSql("delete SYS_USER_ROLES where user_ID='" + userID + "'");
        }


        public void Save(UserRole entity)
        {
            try
            {
                if (entity != null)
                {
                    
                    entity.Save();
                }
            }
            catch(Exception err)
            {

            }
        }
    }
}
